package cn.symbio.org.service.impl;

import cn.symbio.basic.config.BussinessException;
import cn.symbio.basic.query.BaseQuery;
import cn.symbio.basic.util.BaiduAuditUtils;
import cn.symbio.basic.util.EmailUtils;
import cn.symbio.basic.util.PageList;
import cn.symbio.org.domain.Employee;
import cn.symbio.org.domain.Shop;
import cn.symbio.org.domain.ShopAuditLog;
import cn.symbio.org.en.ShopStateEn;
import cn.symbio.org.mapper.EmployeeMapper;
import cn.symbio.org.mapper.ShopAuditLogMapper;
import cn.symbio.org.mapper.ShopMapper;
import cn.symbio.org.service.IShopService;
import cn.symbio.basic.service.impl.BaseServiceImpl;
import cn.symbio.org.vo.EchartsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bitter
 * @since 2022-10-15
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {


    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    // 注入邮件对象
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void settlement(Shop shop) {
        // 获取shop中管理员
        Employee admin = shop.getAdmin();
        Employee emp = verify(shop, admin);
        // ---------------存shop和emp--------------
        // 先存shop店铺
        shopMapper.add(shop);
        // 再存emp,如果查询出来的emp是空就将shop中admin赋值给他并添加（好像直接可以传admin？）
        if (null == emp) {
            emp = admin;
            employeeMapper.add(emp);
        }
        // -----------------分别修改店铺的管理员id和管理员的店铺id--------------------
        Shop shop2 = new Shop();
        // 需要通过id进行修改
        shop2.setId(shop.getId());
        // 添加管理员id
        shop2.setAdminId(emp.getId());
        shopMapper.update(shop2);
        // 修改管理员店铺id
        emp.setShopId(shop.getId());
        employeeMapper.update(emp);
    }

    /**
     * 审核通过
     * @param auditLog
     */
    @Override
    public void pass(ShopAuditLog auditLog) {
        // 非空判断
        if (null == auditLog.getNote()) {
            throw new BussinessException("备注不能为空！！！");
        }
        // 修改店铺状态
        Shop shop = new Shop();
        shop.setId(auditLog.getShopId());
        shop.setState(1);
        shopMapper.update(shop);
        // 添加店铺日志
        // 登录没做，暂时写死
        auditLog.setShopId(shop.getId());
        auditLog.setAuditId(0731);
        auditLog.setState(1);
        shopAuditLogMapper.add(auditLog);
        // 调用工具类发送短信
        try {
            EmailUtils.sendEmail("3489571551@qq.com",
                    "店铺审核结果",
                    "<h1>恭喜你审核通过，点击下方连接即可激活</h1><br/>"+
                            "http://localhost/shop/uptState/"+auditLog.getShopId(),
                    "834291384@qq.com");
        } catch (Exception e) {
            throw new BussinessException("邮件发送失败！！");
        }
    }

    // 用户点击启用，单纯修改状态
    @Override
    public void uptStats(Long id) {
        // 将状态改为已激活
        Shop shop = new Shop();
        shop.setId(id);
        shop.setState(2);
        shopMapper.update(shop);
    }

    @Override
    public Map<String, Object> echarts() {
        Map<String, Object> result = new HashMap<>();
        List<EchartsVo> echarts = shopMapper.echarts();
        // 将EchartsVo中getState转成list存到map中
        List<Long> x = echarts.stream().map(EchartsVo::getState).collect(Collectors.toList());
        List<Long> y = echarts.stream().map(EchartsVo::getCount).collect(Collectors.toList());

        List<String> list = new ArrayList<>();
        for (Long aLong : x) {
            // 调用枚举判断数字对应值
            String nameByCode = ShopStateEn.getNameByCode(aLong);
            list.add(nameByCode);
        }
        // 直接将存有字的集合传到前端
        result.put("x",list);
        result.put("y",y);
        return result;
    }

    // 店铺驳回
    @Override
    public void reject(ShopAuditLog auditLog) {
        // 修改状态为驳回
        Shop shop = new Shop();
        shop.setId(auditLog.getShopId());
        shop.setState(-1);
        shopMapper.update(shop);
        // 存日志
        auditLog.setAuditId(0731);
        auditLog.setShopId(shop.getId());
        shopAuditLogMapper.add(auditLog);
        // 发邮件通知
        try {
            EmailUtils.sendEmail("3489571551@qq.com",
                    "店铺审核结果",
                    "<h1>很遗憾你审核未通过，点击下方连接了解详细</h1><br/>"+
                            "http://localhost:8081/#/registerAgain?shopId="+auditLog.getShopId(),
                    "3489571551@qq.com");
        } catch (Exception e) {
            throw new BussinessException("邮件发送失败！！");
        }
    }

    /**
     * 批量添加
     * @param shops
     */
    @Override
    public void batchAdd(List<Shop> shops) {
        shopMapper.batchAdd(shops);
    }



    // 重写分页查询封装日志进去
    @Override
    public PageList<Shop> queryByPage(BaseQuery query) {
        // 获取条数和数据库
        PageList<Shop> shopPageList = super.queryByPage(query);
        // shop店铺数据
        List<Shop> rows = shopPageList.getRows();
        // 获取店铺id
        List<Long> collect = rows.stream().map(Shop::getId).collect(Collectors.toList());
        // 店铺id获取日志数据
        List<ShopAuditLog> shopAuditLogs = shopAuditLogMapper.getAuditLogByBatchShopId(collect);
        shopAuditLogs.forEach(System.out::println);

//        Map<Long, List<ShopAuditLog>> logMap = shopAuditLogs.stream().collect(Collectors.groupingBy(ShopAuditLog::getShopId));
        // 将数据就封装到map中
        Map<Long,List<ShopAuditLog>> logMap = new HashMap<>();
        // 循环日志
        for (ShopAuditLog log : shopAuditLogs) {
            //
            List<ShopAuditLog> shopAuditLogs1 = logMap.get(log.getShopId());
            if (CollectionUtils.isEmpty(shopAuditLogs1)) {
                shopAuditLogs1 = new ArrayList<>();
            }
            shopAuditLogs1.add(log);
            logMap.put(log.getShopId(),shopAuditLogs1);
        }
        rows.forEach(row->{
            // 将数据存到shop中
            row.setAuditLogs(logMap.get(row.getId()));
        });
        /*for (Shop row : rows) {
            List<ShopAuditLog> shopAuditLogs1 = logMap.get(row.getId());
            row.setAuditLogs(shopAuditLogs1);
        }*/
        return shopPageList;
    }

   /* // 重写分页查询封装日志进去
    @Override
    public PageList<Shop> queryByPage(BaseQuery query) {
        // 条数
        Integer integer = shopMapper.queryByCount(query);
        // 店铺数据
        List<Shop> shops = shopMapper.queryByPage(query);
        for (Shop shop : shops) {
            // shop中日志集合
            List<ShopAuditLog> auditLogs = shop.getAuditLogs();
            // 店铺id去查日志
            List<ShopAuditLog> auditLogByShopId = shopAuditLogMapper.getAuditLogByShopId(shop.getId());
            for (ShopAuditLog shopAuditLog : auditLogByShopId) {
                auditLogs.add(shopAuditLog);
            }
        }
        return new PageList<>(integer,shops);
    }*/



    private Employee verify(Shop shop, Employee admin) {
        // 数据校验
        if (StringUtils.isBlank(shop.getName())) {
            throw new BussinessException("密码不能为空！！");
        } else if (StringUtils.isBlank(shop.getAddress())) {
            throw new BussinessException("地址不能为空！！");
        }
        // 校验两次密码是否一致
        if (!admin.getPassword().equals(admin.getComfirmPassword())) {
            throw new BussinessException("两次密码不一致！！");
        }
        // 百度AI校验合规
        if (!BaiduAuditUtils.TextCensor(shop.getName())) {
            throw new BussinessException("店铺名不合规！！");
        }
        if (!BaiduAuditUtils.ImgCensor(shop.getLogo())) {
            throw new BussinessException("店铺Logo不合规,存在低俗黄色！！");
        }

        // 判断店铺是否存在
        Shop shop1 = shopMapper.findByName(shop.getName());
        if (null != shop1) {
            throw new BussinessException("店铺已存在！！");
        }
        // 判断管理员是否存在和是否关联店铺
        Employee emp = employeeMapper.findByName(admin.getUsername());
        // 都不为空再判断是否与当前店铺管理
        if (null != emp && null != emp.getShopId()) {
            Shop shopById = shopMapper.findById(emp.getShopId());
            // 判断是否与当前emp是不是当前店铺管理员
            if (shopById.getAdminId().equals(emp.getShopId())) {
                throw new BussinessException("管理员已关联店铺！！");
            }
        }
        return emp;
    }
}
